import { ref } from "vue";

export const useAudioAutoPlay = () => {
  const hasUserInteracted = ref(false);
  const audioRef = ref<HTMLAudioElement | null>(null);

  // 音频播放函数
  const playAudio = (options: { mute?: boolean } = {}) => {
    if (audioRef.value) {
      if (options.mute) {
        audioRef.value.muted = true;
      } else {
        audioRef.value.muted = false;
      }
      audioRef.value.play().catch(error => {
        console.error("Error playing audio:", error);
      });
    }
  };

  // 处理用户首次交互
  const handleFirstInteraction = () => {
    if (!hasUserInteracted.value) {
      hasUserInteracted.value = true;
      // 只解除自动播放限制，不立即播放声音
      playAudio({ mute: true });
      // 移除事件监听器
      document.removeEventListener("click", handleFirstInteraction);
      document.removeEventListener("touchstart", handleFirstInteraction);
    }
  };

  // 初始化音频自动播放
  const initAudioAutoPlay = () => {
    document.addEventListener("click", handleFirstInteraction);
    document.addEventListener("touchstart", handleFirstInteraction);
  };

  // 清理音频自动播放
  const cleanupAudioAutoPlay = () => {
    document.removeEventListener("click", handleFirstInteraction);
    document.removeEventListener("touchstart", handleFirstInteraction);
  };

  return {
    audioRef,
    hasUserInteracted,
    playAudio,
    initAudioAutoPlay,
    cleanupAudioAutoPlay
  };
};
